/**
 * Copyright (c) 2010-2011 julewa.com.  
 * All rights reserved. 
 * 
 * @author Huang Benhua
 * @date 2011-2-20
 * 
**/
package com.julewa.freemarker;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import com.julewa.loading.SystemUtils;
import com.julewa.utils.StreamUtils;

import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreemarkerBuilder {
	private Template template; 
	private Map<String, Object> parameters;
	public FreemarkerBuilder(Template template){
		this.template = template;
		this.parameters = new HashMap<String, Object>();
	}
	
	public Map<String, Object> getParameters(){
		return parameters;
	}
	
	public void setParameters(Map<String, Object> map){
		parameters = map;
	}
	
	public void put(String key, Object value){
		parameters.put(key, value);
	}
	
	public boolean build(Writer writer){
		try {
			template.process(parameters, writer);
			return true;
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public boolean build(String file){
		File f = new File(file);
		try {
			if(!f.exists())f.createNewFile();
			FileWriter fw = new FileWriter(f);
			if(!build(fw)){
				fw.close();
				return true;
			};
			fw.close();
			if(SystemUtils.isDebug()){
				System.out.println("[debug] file created: " + file);
				file = StreamUtils.readText(new FileInputStream(file));
				System.out.println(file);
			};
			return true;
		} catch (IOException e){
			System.err.println("Failed to create file: " + file);
			e.printStackTrace();
		}
		return false;
	}
}
